package com.bzchao.ds.demo.common.config.ds;

import com.bzchao.ds.core.config.DynamicDataSource;
import com.bzchao.ds.demo.common.config.constant.BaseConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录请求拦截器
 */
@Slf4j
public class TenantIdInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        String tenantId = request.getHeader(BaseConstants.X_TENANT_ID);
        if (!StringUtils.hasLength(tenantId)) {
            log.warn("401 - {}", request.getRequestURI());
            throw new RuntimeException("请携带租户ID");
        }

        DynamicDataSource.switchConnect(tenantId);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        DynamicDataSource.clearDataSource();
    }
}
